<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * @package       Pfw
 * @author        Sean Sitter <sean@picnicphp.com>
 * @copyright     2010 The Picnic PHP Framework
 * @license       http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0
 * @link          http://www.picnicphp.com
 * @since         0.10
 * @filesource
 */

/**
 * Short description for file
 *
 * Long description for file (if any)...
 * 
 * @category      Framework
 * @package       Pfw
 */
abstract class Pfw_Paginator
{
    const DEFAULT_PER_PAGE = 10;

    protected $offset;
    protected $per_page;
    protected $page_num;
    protected $last_page_num;
    protected $collection;
    protected $total;

    abstract public function paginate();
    abstract public function getTotal();

    /**
     * @param int $per_page
     * @param int $page_num
     */
    public function __construct($page_num = 1, $per_page = self::DEFAULT_PER_PAGE)
    {
        $this->per_page = $per_page;
        $this->page_num = $page_num;
        $this->collection = null;
    }

    protected function getOffset()
    {
        $this->offset = ($this->getPageNum() - 1) * $this->getPerPage();
        return $this->offset;
    }

    public function setPerPage($per_page)
    {
        if ($this->per_page != intval($per_page)) {
            $this->per_page = intval($per_page);
            $this->collection = null;
        }
    }

    public function getPerPage()
    {
        return $this->per_page;
    }

    public function setPageNum($page_num)
    {
        if ($this->page_num != intval($page_num)) {
            $this->page_num = intval($per_page);
            $this->collection = null;
        }
    }

    public function getPageNum()
    {
        return $this->page_num;
    }

    public function getLastPageNum()
    {
        if (!isset($this->last_page_num)) {
            return $this->last_page_num = intval(ceil($this->getTotal() / $this->getPerPage()));
        }
        return $this->last_page_num;
    }

    public function setQsVarName($qs_var_name)
    {
        if ($this->qs_var_name != $qs_var_name) {
            $this->qs_var_name = $qs_var_name;
            $this->collection = null;
        }
    }

    public function getQsVarName()
    {
        return $this->qs_var_name;
    }

    public function getQS()
    {
        $page_num = $_GET[$this->qs_var_name];
        $page_num = (!empty($page_num)) ? intval($page_num) : 1;

        $qs_str = "";
        foreach($_GET as $key => $value){
            if($key == $qs_var_name){
                continue;
            }
            $value = urlencode($value);
            $qs_str .= "&{$key}={$value}";
        }
        $amp = (empty($qs_str)) ? "" : "&";
        $qs_str = "?" . $qs_str . "{$amp}{$qs_var_name}=";
    }

    public function resetCache()
    {
        $this->collection = null;
        $this->total = null;
    }
}
